package cz.acies.organizer.data.persist;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.dom.DOMElement;

import cz.acies.data.DBConnector;

public class Calendar implements java.io.Serializable
{
	private static final long serialVersionUID = 6684479529790055016L;

	protected List<CalendarTask> records;
	
	public Calendar() {
		records = new ArrayList<CalendarTask>();
	}

	public String loadXml() {
		String data = "";
		
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			DOMElement root = new DOMElement("data");

			conn = DBConnector.instance().conn();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(
				"SELECT * FROM calendar_task AS rec " +
				//"WHERE rec.UID = 'CA-E-00000000001'" +
				""
			);
			
			String workerId = "WX-L-GZ69V88D4ZW";
			
			while (rs.next()) {
				String id = rs.getString("UID");
				String start_date = rs.getString("DATE_START"); 
				String end_date = rs.getString("DATE_END");
				String text = rs.getString("SUBJECT");
				//text = new String(((String)text, ).getBytes("utf-8"));
				String details = rs.getString("DESCRIPTION");
				
				String userId = rs.getString("USER_ID");
				
				DOMElement event = new DOMElement("event");
				event.addAttribute("id", "" + id);
				event.addElement("start_date").addCDATA("" + start_date); 
				event.addElement("end_date").addCDATA("" + end_date);
				event.addElement("text").addCDATA("" + text);
				event.addElement("details").addCDATA("" + details);
				if (!userId.equals(workerId)) {
					event.addElement("color").addText("#00fcc0");
				}
				event.addElement("section_id").addCDATA("" + userId);
				
				root.add(event);
			}
			data = root.asXML();
			System.out.println("xml: " + data);
			
		} catch (Exception exc) {
			exc.printStackTrace();
		} finally {
			try { if (rs != null) rs.close(); } catch (Exception e) {}
			try { if (stmt != null) stmt.close(); } catch (Exception e) {}
			try { if (conn != null) conn.close(); } catch (Exception e) {}
		}
		return data;
	}
	
	public String asXml() {
		String xml = "";
		return xml;
	}
	
	public static void main(String[] args) {
		try {
			Calendar c = new Calendar();
			System.out.println(c.loadXml());
		} catch (Exception exc) {
			exc.printStackTrace();
		}
	}
	
}
